package impl

import (
	"context"
	"errors"
	"time"
	"wms/entity"
	"wms/glo"
	"wms/service/model"
	"wms/service/request"
	"wms/util"

	"github.com/acmestack/gorm-plus/gplus"
)

type WarehouseService struct {
}

var WarehouseSrvImpl WarehouseService

func (s *WarehouseService) List(ctx context.Context, arg *request.QueryWarehouseRequest) []*model.Warehouse {
	entities, resultDb := gplus.SelectList[entity.Warehouse](nil)
	if resultDb.Error != nil {
		panic("sql err" + resultDb.Error.Error())
	}
	//
	modelListOut := make([]*model.Warehouse, 0, len(entities))
	for _, tmp := range entities {
		_w := new(model.Warehouse)
		util.CopyStruct(_w, tmp)
		modelListOut = append(modelListOut, _w)
	}
	return modelListOut
}

func (s *WarehouseService) Add(ctx context.Context, arg *request.AddWarehouseRequest) error {
	query, u := gplus.NewQuery[entity.Warehouse]()
	query.Eq(&u.WarehouseCode, arg.WarehouseCode)
	_, resultDb := gplus.SelectOne(query)
	if resultDb.RowsAffected > 0 {
		return errors.New("编码:" + arg.WarehouseCode + "已存在")
	}
	addEntity := new(entity.Warehouse)
	util.CopyStruct(addEntity, arg)
	//
	resultDb = gplus.Insert(&addEntity)
	if resultDb.Error != nil {
		return errors.New("insert warehouse err:" + resultDb.Error.Error())
	}
	util.Log("warehouse id:", addEntity.WarehouseID)
	return nil
}

func (s *WarehouseService) Edit(ctx context.Context, arg *request.EditWarehouseRequest) error {
	warehouse, resultDb := gplus.SelectById[entity.Warehouse](arg.WarehouseID)
	if resultDb.Error != nil {
		return errors.New("select warehouse err:" + resultDb.Error.Error())
	}
	util.CopyStruct(warehouse, arg)
	warehouse.UpdatedAt = time.Now()
	util.Log("warehouse arg:", *arg, "db:", *warehouse)
	// glo.Db_wms.Begin() glo.Db_wms.Create()
	if err := glo.Db_wms.Save(warehouse).Error; err != nil {
		return errors.New("update warehouse err:" + err.Error())
	}
	// m := gplus.GetModel[entity.Warehouse]()
	// select db 的小写下划线名字 update是可以不用写的
	// optFunc := gplus.Select(&m.Enable, &m.WarehouseCode, &m.WarehouseName, &m.Supervisor, &m.Tel, &m.Address)
	// resultDb = gplus.UpdateById(&warehouse, optFunc)
	//resultDb = gplus.UpdateById(warehouse)
	//if resultDb.Error != nil {
	//	return errors.New("update warehouse err:" + resultDb.Error.Error())
	//}

	return nil
}
